﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace CommonTools.FinancialTextbox
{
    public partial class DataGridIntegerTextEditColumn : DataGridViewTextBoxEditingControl
    {
        public DataGridIntegerTextEditColumn()
        {
            InitializeComponent();
            this.KeyPress += new KeyPressEventHandler(DataGridIntegerTextEditColumn_KeyPress);
            this.Leave += new EventHandler(DataGridIntegerTextEditColumn_Leave);
            this.Enter += new EventHandler(DataGridIntegerTextEditColumn_Enter);
        }

        void DataGridIntegerTextEditColumn_Enter(object sender, EventArgs e)
        {
            this.Text = this.Text.Trim().Replace(",", "");
        }

        void DataGridIntegerTextEditColumn_Leave(object sender, EventArgs e)
        {
            try
            {
                long l = long.Parse(this.Text.Trim());
                this.Text = Helper.MoneyString(l);

            }catch { this.Text = "0";}
        }
        public long Value
        {
            get {
                return Helper.StringToLong(this.Text);
            }
            set
            {
                this.Text = Helper.MoneyString(value);
            }
        }
        void DataGridIntegerTextEditColumn_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')) e.Handled = true;
        }

        public DataGridIntegerTextEditColumn(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
            //this.KeyPress += new KeyPressEventHandler(DataGridIntegerTextEditColumn_KeyPress);
            //this.Leave += new EventHandler(DataGridIntegerTextEditColumn_Leave);
            //this.Enter += new EventHandler(DataGridIntegerTextEditColumn_Enter);
            this.TextChanged += new EventHandler(this.Format_TextBox);
        }

        private void Format_TextBox(object sender, EventArgs e)
        {
            string s = ((TextBox)sender).Text.Trim();
            char[] ch = s.ToCharArray();

            StringBuilder sb = new StringBuilder();

            foreach (char c in ch)
            {
                if (Char.IsDigit(c))
                {
                    sb.Append(c);
                }
            }

            if (sb.Length >= 1)
            {
                ((TextBox)sender).Text = Convert.ToDecimal(sb.ToString()).ToString("N0");
                ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
            }
            else
            {
                ((TextBox)sender).Clear();
            }
        }
    }
}
